Using :nth-child() and :nth-of-type() for Odd and Even Elements
CSS pseudo-classes :nth-child() and :nth-of-type() allow you to select elements based on their position. You can use them to target every odd or even element efficiently.
:nth-child(even) – Selects every even child of its parent (2nd, 4th, 6th, etc.).
:nth-child(odd) – Selects every odd child of its parent (1st, 3rd, 5th, etc.).
:nth-of-type(even) – Selects every even element of the specified type among siblings.
:nth-of-type(odd) – Selects every odd element of the specified type among siblings.
In this example, :nth-child(even) and :nth-child(odd) alternate the background color of all list items, while :nth-of-type(even) makes every even <li> bold, ignoring other sibling element types.
Use :nth-child() when you want to style elements based on their absolute position among all children.
Use :nth-of-type() when styling elements of a specific type among siblings.
Combine odd/even pseudo-classes with other selectors for more precise styling.
Test in complex HTML structures to ensure the desired elements are targeted correctly.